import * as api from '../../api/api.js';
import db from '../../utils/db.js';
import { ASSETS } from '../../config.js';
import { RewardedVideoAd } from '../../utils/rewarded-video-ad.js';
const app = getApp();
const os = app.os;
let methodMark = 1; //1未下单退出;2已下单退出;3完成支付退出;4支付失败

Component({
  adTimerId: 0,
  data: {
    assets: ASSETS,
    iosDyPayType: 0, //2=IM支付,3=钻石支付
    isIPhone: app.isIPhone(),
    rechangeTitle: '',
    rechangeMoney: '0',
    rechangeCoin: '0',
    showGuideTips: false,
    isNoPayOrder: false,
    currentGearType: 1,
    orderId: '',
    countdown: app.globalData.adCountdown, //倒数读秒
    timeCount: app.globalData.adCountdown, //填写同上
  },
  properties: {
    // 1=广告挽留弹框,2=付费挽留弹框,3=退出挽留弹框,4=天降福利广告解锁弹窗
    type: {
      type: Number,
      value: 1,
      observer(value){
        this.setData({
          countdown: app.globalData.adCountdown,
          timeCount: app.globalData.adCountdown,
          type: value
        });
      }
    },
    show:{
      type:Boolean,
      value:false,
    },
    mask:{
      type:Boolean,
      value:false,
    },
    data:{
      type: Object,
      value: {},
      observer(value){
        this.setData({
          data: value
        });
      }
    },
    currentVideo: {
      type: Object,
      value: {},
      observer(value){
        this.setData({
          currentVideo: value
        });
      }
    },
    currentAblum: {
      type: Object,
      value: {},
      observer(value){
        this.setData({
          currentAblum: value
        });
      }
    }
    
  },
  ready() {
    const that = this;
    if (this.data.type === 3 || this.data.type == 4) {
      this.autoPullupAd();
    }
  },
  methods: {
    
    onCreateOrder(){
      if (!app.isCanBuy()) {
        app.Tips({title: 'iOS 暂不支持购买'});
        return;
      }
      
      const item = this.data.data;
      os.showLoading({
        title: '请稍候...',
        mask: true
      });
  
      let logsData = app.getLogsData('pay', 4, {
        payment_id: item.gear_id,
        method_id: this.data.currentVideo?.playlet_id || 0,
        method_cid: this.data.currentVideo?.num || 0
      });
      api.createOrder({
        playlet_id: this.data.currentVideo?.playlet_id || 0,
        gear_id: item.gear_id,
        retain_id: item.retain_id,
        logs: JSON.stringify(logsData)
      }).then(res => {
        os.hideLoading({});
        if (res.code == 200) {
          methodMark = 2;
          const data = JSON.parse(res.data.data);
          const payScene = data?.payScene || "";
          const currency = data?.currency || "";
          this.setData({
            orderId: res.data.order_id,
            currentGearType: item.gear_type_id,
            iosDyPayType: payScene === "IM" ? 2:(currency === 'DIAMOND' ? 3:0)
          });
          this.createOrder(res.data);
        }else{
          app.Tips({title: res.msg});
          if (res.code === 201) {
            this.confirm();
            return;
          }
          this.sendAppLogs('pay', 6, {
            method_mark: res.msg,
            method_mark_1: res.code
          });
        }
      }).catch(err => {
        os.hideLoading({});
      });
    },

    createOrder(res){
      os.requestOrder({
        data: res.data, 
        byteAuthorization: res.byteAuthorization,
        success: (res) => {
          // app.echo(res)
          app.echo('orderId', res.orderId);
          this.openOrderPayment(res.orderId);
        },
        fail: (res) => {
          app.echo('requestOrder error', res);
          app.Tips({title: '下单失败', icon: 'fail'});
          this.sendAppLogs('pay', 6, {
            method_mark: res.errMsg,
            method_mark_1: res.errNo
          });
        },
      });
    },

    openOrderPayment(orderId){
      os.showLoading({
        title: '安全支付中...',
        mask: true
      });
      let parms = {
        orderId: orderId,
        success: (res) => {
          os.hideLoading({});
          methodMark = 3;
          this.setData({isNoPayOrder: true});
          db.saveNoPayOrder(this.data.orderId);
          this.queryOrder();
        },
        fail: (res) => {
          os.hideLoading({});
          methodMark = 4;
          app.echo('getOrderPayment error', res);
          if (res.errNo === 9) {
            this.setData({isNoPayOrder: true});
            db.saveNoPayOrder(this.data.orderId);
            this.queryOrder(3);
          } 
          if (res.errNo === 4) {
            app.Tips({title: '支付取消', icon: 'fail'});
          } 
          if (res.errNo !== 4 && res.errNo !== 9) {
            app.Tips({title: '支付失败', icon: 'fail'});
          } 

          this.sendAppLogs('pay', 6, {
            method_mark: res.errMsg,
            method_mark_1: res.errNo
          });
        },
        complete: (res) => {
          // db.saveNoPayOrder(this.data.orderId);
          // this.setData({isNoPayOrder: true});
        }
      };

      if (this.data.iosDyPayType === 2 && app.isIPhone() && os.canIUse("getOrderPayment.object.immediate")) {
        parms.immediate = false;
        parms.imId = app.globalData.imId;
      }

      os.getOrderPayment(parms);
    },

    queryOrder(type = 0){
      os.showLoading({
        title: '请稍候...',
        mask: true
      });
      api.queryOrder({
        order_id: this.data.orderId
      }).then(res => {
        app.echo(res);
        os.hideLoading({});
        if (res.code == 200) {
          this.confirm();
        }else{
          app.echo('queryOrder error', res);
          // app.Tips({title: res.msg});
          this.sendAppLogs('pay', 6, {
            method_mark: res.msg,
            method_mark_1: res.code
          });
          if (type === 0) {
            app.Tips({title: '请稍后查看到账情况'});
          }
          if (type === 1) {
            this.cancel();
          }
          if (type === 2) {
            this.setData({isNoPayOrder: false});
            app.Tips({title: '请稍后重试'});
          }
          if (type === 3) {
            app.Tips({title: '支付失败', icon: 'fail'});
          }
        }
      }).catch(err => {
        os.hideLoading({});
        if (type === 1) {
          this.cancel();
        }
        if (type === 0 && this.data.currentGearType !== 1) {
          this.confirm();
        }
      });
    },

    closeDialog(){
      // 未支付订单
      if (this.data.isNoPayOrder) {
        this.queryOrder(1);
        return;
      }
      this.cancel();
    },

    confirm() {
      if (this.data.type == 3 || this.data.type == 4) {
        this.clearAdTimer();
      }

      this.setData({
        show: false,
        showGuideTips: false,
        isNoPayOrder: false
      });

      this.triggerEvent('confirm', {
        type: parseInt(this.data.type), 
        data: this.data.data
      });

      if (this.data.type == 2) {
        db.delNoPayOrder();
        this.sendAppLogs('pay', 3, {
          method_mark: 3
        });
      }
    },
    cancel(type = 0) {
      this.setData({
        show: false,
        showGuideTips: false,
        isNoPayOrder: false
      });

      if (this.data.type == 3 || this.data.type == 4) {
        this.clearAdTimer();
      }

      this.triggerEvent('cancel', {
        type: type !== 0 ? type: parseInt(this.data.type), 
        data: this.data.data
      });

      if (this.data.type == 2) {
        this.sendAppLogs('pay', 3, {
          method_mark: methodMark
        });
      }
    },
    
    adFreeUnlock() {
      this.setData({
        show: false,
        showGuideTips: false,
        isNoPayOrder: false
      });
      this.triggerEvent('confirm', {
        type: 'adFreeUnlock', 
        data:[]
      });
    },

    toAgreementPage(e){
      app.goNewsPage(parseInt(e.currentTarget.dataset.id));
    },

    openGuideDialog(){
      this.setData({showGuideTips: true});
    },

    closeGuideDialog(){
      this.setData({showGuideTips: false});
    },

    sendAppLogs(logType = 'app', markType = 1, data = {}){
      const currentVideo = this.data.currentVideo;
      let rData = {};
      if (currentVideo) {
        rData = {
          method_id: currentVideo.playlet_id || 0, 
          method_cid: currentVideo.num || 0,
          method_rid: parseInt(currentVideo?.fromPlayletId || 0),
          method_amount: currentVideo.currentTime || 0
        };
      }
      rData.order_id = this.data.orderId;
      Object.assign(rData, data);
      app.sendAppLogs(logType, markType, rData);
    },

    autoPullupAd() {
      const _this = this;
      const timeCount = this.data.timeCount;
      if (app.globalData.appType === 1) {
        if (this.adTimerId > 0) {
          clearInterval(this.adTimerId);
        }
        this.data.countdown = timeCount;
        this.setData({
          countdown: timeCount
        });
      
        this.adTimerId = setInterval(function(){
          const countdown = _this.data.countdown - 1;
          if(countdown <= 0){
            _this.clearAdTimer();
            if (_this.data.type === 3) {
              _this.openRewardedVideoAd();
            }
            if (_this.data.type === 4) {
              _this.confirm();
            }
            return;
          }
          _this.data.countdown = countdown;
          _this.setData({
            countdown: countdown
          });
        }, 1000);
      }
    },

    clearAdTimer(){
      if (this.adTimerId > 0) {
        clearInterval(this.adTimerId);
        this.adTimerId = 0;
        this.data.countdown = this.data.timeCount;
      }
    },

    /**
     * 打开激励视频广告
     */
    openRewardedVideoAd(){
      const _this = this;
      let { currentAblum } = this.data;
      if (currentAblum === false) {
        return;
      }

      if (this.videoAd !== undefined) {
        this.videoAd.destroy();
        setTimeout(function(){
          _this.videoAd.show();
        }, 50);
        return;
      }
  
      this.videoAd = new RewardedVideoAd({
        onAdConfChange: (res) => {
          if (res.type === 1) {
            app.setGlobalData('adverConfig', res.data);
          } else {
            app.setGlobalData('currentAdConf', res.data);
          }
        },
        onLoad: (res) => {
          if(res.type === 'success'){
            _this.sendAppLogs('iaa', 2, {
              method_mark: '加载成功',
              method_mark_1: 200
            });
          }
          if(res.type === 'reg'){
            _this.sendAppLogs('iaa', 1);
          }
        },
        onShow: () => {
          _this.sendAppLogs('iaa', 4);
        },
        onClose: (res) => {
          if (res.isEnded) {
            _this.updateUnlockVideo();
            _this.sendAppLogs('iaa', 6, {
              method_mark: 1, 
              method_mark_1: res.second
            });
          } else {
            _this.cancel('closeAd');
            _this.sendAppLogs('iaa', 6, {
              method_mark: 0, 
              method_mark_1: res.second
            });
            
          }
        },
        onError:(error) => {
          app.Tips({title: '拉取广告失败，请稍后重试'});
          _this.sendAppLogs('iaa', 3, {
            method_mark: error.errMsg || '', 
            method_mark_1: error.errCode || ''
          });
        }
      });
    },

    /**
     * 更新解锁状态
     */
    updateUnlockVideo(){
      const _this = this;
      let { currentAblum} = this.data;
      if (currentAblum === false) {
        this.cancel();
        return;
      }

      const backUnlockNum = currentAblum?.back_unlock_num || 1;
      let allVideoData = currentAblum?.list || [];
      let unlockIds = [];

      allVideoData.forEach((item, index) => {
        if (item.is_unlock === 1 && unlockIds.length < backUnlockNum) {
          unlockIds.push(item.chapter_id);
        }
      });

      if (unlockIds.length > 0) {
        api.advertUnlockPlaylet({
          chapter_ids: unlockIds.join(','), 
          playlet_id: currentAblum.playlet_id,
          ad_id: app.globalData.currentAdConf?.advert_id || 0
        }, {showErr: false}).then(res => {
          _this.confirm();
        }); // 保存解锁状态

        unlockIds.forEach((item, index) => {
          let cVideo = allVideoData?.find(i => i.chapter_id == item);
          this.sendAppLogs('video', 14, {
            method_cid: cVideo?.num || 0,
            method_amount: 0,
            method_mark: 3
          }); 
        });
      } else {
        this.confirm();
      }
    },

  }
})